package com.cy.aircompressor.main.welcome.fragment;

import android.os.Bundle;
import android.text.TextUtils;

import androidx.lifecycle.Observer;

import com.cy.aircompressor.config.AirConfig;
import com.cy.aircompressor.databinding.ActivitySplashBinding;
import com.cy.aircompressor.entity.system.UserInfo;
import com.cy.aircompressor.main.home.MainActivity;
import com.cy.aircompressor.main.welcome.viewmodel.WelcomeViewModel;
import com.cy.aircompressor.utils.JumpPageUtils;
import com.drug.lib.util.SPManager;
import com.drug.lib.util.ToastUtil;
import com.net.model.base.Resource;
import com.net.model.base.fragment.BaseVMFragment;
import com.net.model.livedatas.LiveDataBus;

public class SplashFragment extends BaseVMFragment<ActivitySplashBinding, WelcomeViewModel> {
    public static SplashFragment newInstance() {
        Bundle args = new Bundle();
        SplashFragment fragment = new SplashFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected ActivitySplashBinding getViewBinding() {
        return ActivitySplashBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        if (AirConfig.get().isLoginFlag()) {
            JumpPageUtils.jumpMain();
        } else {
            if (!TextUtils.isEmpty(SPManager.getPassWord()) &&
                    !TextUtils.isEmpty(SPManager.getUserName()) &&
                    SPManager.getRememberPassword()) {
                mViewModel.login(SPManager.getUserName(), SPManager.getPassWord());
            } else {
                JumpPageUtils.jumpLogin();
            }
        }
    }

    @Override
    protected void requestNetwork() {

    }

    @Override
    protected void dataChange() {
        mViewModel.getLoginObservable().observe(this, boserver -> {
            boserver.handler(new OnCallback<String>() {
                @Override
                public void onSuccess(String data) {
                    SPManager.setToken(data);
                    AirConfig.get().updateLoginFlag(true);
                    JumpPageUtils.jumpMain();
                }

                @Override
                public void onFailure(Integer code, String message) {
                    super.onFailure(code, message);
                    ToastUtil.show(message);
                    JumpPageUtils.jumpLogin();
                }
            });
        });
    }
}
